
import { loginByUserName } from '@/api/login'

export default {
  namespaced: true,
  state: {
    userInfo: {
      id: 0,
      userName: '',
      client_id: 'client_2',
      client_secret: '123456',
      scope: 'server',
      grant_type: 'password'
    },

   /* loginUserInfo: {
      id: null,
      userName: null
    },*/

    permissionList: [], // 权限列表
    menuList: [], // 菜单列表
    tokenInfo: {
      access_token: '',
      refresh_token: '',
      expires_in: 0,
      token_type: '' // 此处置空，不知道什么鬼不知空后台远程服务调用一直报错，导致登录一直提示用户不存在
    }
  },

  actions: {
    login ({commit}, userInfo) {
      return new Promise((resolve, reject) => {
        loginByUserName(userInfo).then(response => {
          let data = response.data
          if (data.access_token) {
            let tokenInfo = {
              access_token: data.access_token,
              refresh_token: data.refresh_token,
              expires_in: data.expires_in,
              token_type: 'Bearer '
            }
            commit('updateTokenInfo', tokenInfo)
            console.log(data)
          }
          resolve(data)
        }).catch(error => {
          reject(error)
        })
      })
    }
  },

  getters: {

    getUserInfo (state) {
     /* if (!state.userInfo.username) {
        let data = JSON.parse(localStorage.getItem('userInfo'))
        if (data) {
          return data
        }
      }*/
      return state.userInfo
    },

    getMenuList (state) {
      if (state.menuList.length === 0) {
        let data = JSON.parse(localStorage.getItem('menuList'))
        if (data) {
          return data
        }
      }
      return state.menuList
    },

    getPermissionList (state) {
      if (state.permissionList.length === 0) {
        let data = JSON.parse(localStorage.getItem('permissionList'))
        if (data) {
          return data
        }
      }
      return state.permissionList
    },

    getTokenInfo (state) {
      if (!state.tokenInfo.access_token) {
        let data = JSON.parse(localStorage.getItem('tokenInfo'))
        if (data) {
          return data
        }
      }
      return state.tokenInfo
    }
  },

  mutations: {

    updateUserInfo (state, userInfo) {
      state.userInfo = userInfo
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
    },

    updateTokenInfo (state, tokenInfo) {
      state.tokenInfo = tokenInfo
      localStorage.setItem('tokenInfo', JSON.stringify(tokenInfo))
    },

    updateMenuList (state, menuList) {
      state.menuList = menuList
      localStorage.setItem('menuList', JSON.stringify(menuList))
    },

    updatePermissionList (state, permissionList) {
      state.permissionList = permissionList
      localStorage.setItem('permissionList', JSON.stringify(permissionList))
    }
  }
}
